package cn.com.nes.site.handle.serializer;

import cn.com.nes.site.entity.em.IEnum;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;

@Slf4j
public class EnumDeserializer<T extends IEnum> extends JsonDeserializer<IEnum> implements Serializable {

    @Override
    public IEnum deserialize(JsonParser parser,
            DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        final String text = parser.getText();
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        JsonStreamContext parsingContext = parser.getParsingContext();
        String currentName = parsingContext.getCurrentName();
        Object currentValue = parsingContext.getCurrentValue();

        Field declaredField = null;
        try {
            declaredField = currentValue.getClass().getDeclaredField(currentName);
        } catch (NoSuchFieldException e) {
            log.error("No such field warning: " + currentName, e);
            return null;
        }
        Class<?> targetType = declaredField.getType();
        if (!IEnum.class.isAssignableFrom(targetType)) {
            return null;
        }
        T[] values = (T[]) targetType.getEnumConstants();
        for (T t : values) {
            if (text.equals(t.getKey().toString())) {
                return t;
            }
        }
        return null;
    }

}
